<template>
  <div class="shb-main">
    <div :style="getWatermaskStyle({ content: watermaskContent, zIndex: 9999 })"></div>
    <div id="cti-wincall" style="display:none"></div>
    <!-- start 企业版新功能试用 -->
    <el-alert
      v-if="notificationShow"
      :title="notification.title"
      type="warning"
      show-icon
      @close="closeNotification">
    </el-alert>
    <!-- end 个人体验版 -->

    <!-- start 企业版新功能试用 -->
    <wei-xin-apply-trail-feature v-if="isShowTrail" @close="handlerTrailClose" />
    <!-- end 企业版新功能试用 -->

    <!-- start 飞书企业版新功能试用 -->
    <lark-apply-trail-feature ref="larkApplyTrailFeature" v-if="isShowLarkTrail" @close="handlerLarkTrailClose" :tenantName="tenantName"/>
    <!-- end 飞书企业版新功能试用 -->

    <!-- start 个人体验版 -->
    <personal-version-opening-guide v-if="isPersonalVersion" />
    <!-- end 个人体验版 -->

    <!-- <div class="frame-quick-notification" v-show="notificationShow">
      <div class="frame-quick-notification-info" ref="notificationInfo">
        <span class="frame-quick-notification-icon"><i class="iconfont icon-info"></i></span>
        <div class="frame-quick-notification-content" ref="notificationContent">
          <p
            ref="notificationText"
            class="frame-quick-notification-text"
          >{{ notification.title }}</p>
        </div>
      </div>
      <button type="button" @click="closeNotification" class="reset-btn icon-btn round frame-quick-notification-close-btn">
        <i class="iconfont icon-close"></i>
      </button>
    </div> -->
    <div class="frame">
      <frame-nav :collapse.sync="collapse"
                 :source="navBarMenus"
                 :more-menus="moreMenus"
                 :new-logo="logoImg"
                 :default-active="defaultActive"
                 @open="openForNav"
                 @open-home="openHome"
                 @collapse-changed="adjustOpenTab"
                 v-if="showNavBar && (!initData.from || initData.from !== 'ddcrm')" />
      
      <div class="frame-content">
        <header class="frame-header">
          <div id="user-feed-back-guide"></div>
          <div class="frame-quick">
            <div class="frame-quick-left">
              <button
                v-if="showNavBar && (!initData.from || initData.from !== 'ddcrm')"
                type="button"
                class="btn-text frame-header-btn frame-collapse frame-header-btn-bg"
                @click="frameHeaderBtn()"
								v-track="$track.formatParams('NAV_COLLAPSE')"
              >
                <i :class="['iconfont', collapse ? 'icon-open' : 'icon-Takeup']"></i>
              </button>

              <button
                v-if="initData.from && initData.from == 'ddcrm'"
                type="button"
                class="base-btn"
                @click="goback"
              >
                <i class="iconfont icon-left"></i>
                {{$t('common.base.back')}}
              </button>

              <frame-tab-group ref="frameTabGroupRef" :tabs.sync="frameTabs" @jump="jumpFrameTab" @reload="reloadFrameTabByFrameView" @close="ProcessingPage" @closeAll="pageCloseAll" @closeOther="pageCloseOther" />

            </div>

            <!-- profile -->
            <div v-if="!initData.from || initData.from !== 'ddcrm'" class="frame-quick-right">
              
              <!-- 快捷入口 -->
              <express-entrance :init-data="initData" />

              <!-- start 智齿呼叫中心 -->
              <call-center-zhi-chi v-if="callCenterType == 1" />
              <!-- end 智齿呼叫中心 -->

              <!-- start 天润呼叫中心 -->
              <call-center-tian-run v-if="callCenterType == 3" />
              <!-- end 天润呼叫中心 -->

              <!-- start 中通天鸿呼叫中心 -->
              <call-center v-if="callCenterType == 0"/>
              <!-- end 中通天鸿呼叫中心 -->
              <el-popover v-if="showDevTool">
                <button type="button" class="btn-text frame-header-btn dev-tool" slot="reference">
                  <i class="iconfont icon-experiment"></i>
                </button>

                <div class="dev-tool-menu">
                  <a href="javascript:;" @click="openEnumTab(key)">路由枚举测试用</a>
                  <a href="javascript:;" @click="openTab('taskTest')">
                    AI NL2Params
                  </a>
                  <a href="javascript:;" v-for="(item, key) in tabMap" :keframe-tab-groupy="key" @click="openTab(key)">{{item.title}}</a>
                  <!-- <a href="javascript:;" @click="openTab('customerServiceStatus_list')">模板工程</a>
                  <a href="javascript:;" @click="openTab('archive_view')">归档工单</a>
                  <a href="javascript:;" @click="clearStorage">清空缓存</a>
                  <a href="javascript:;" @click="openTab('demo')">demo</a>
                  <a href="javascript:;" @click="openTab('calendar')">日程管理</a>
                  <a href="javascript:;" @click="openTab('dept_view')">组织架构管理</a>
                  <a href="javascript:;" @click="openTab('portal_setting')">门户页面设置</a>
                  <a href="javascript:;" @click="openTab('portal')">门户页面设置</a>
                  <a href="javascript:;" @click="openTab('portal_config')">门户页面设置</a>
                  <a href="javascript:;" @click="openTab('role_view')">角色管理</a>
                  <a href="javascript:;" @click="openTab('serviceProvider_view')">服务商管理</a>
                  <a href="javascript:;" @click="openTab('productQrcode')">产品二维码管理</a>
                  <a href="javascript:;" @click="openTab('customer_tag')">客户标签设置</a>
                  <a href="javascript:;" @click="openTab('intelligenceReport')">人效考核-平均响应用时</a>
                  <a href="javascript:;" @click="openTab('customerList')">客户列表快筛</a> -->
                  <a href="javascript:;" @click="openTab('user_view')">{{$t('common.pageTitle.pageSecurityUserView')}}</a>
                  <a href="javascript:;" @click="openTab('subManage')">{{$t('frameHeader.informManage')}}</a>
                  <a href="javascript:;" @click="openTab('smsMessage')">{{$t('common.pageTitle.pageSettingSmsmessage')}}</a>
                  <a href="javascript:;" @click="openTab('messageSetting')">{{$t('frameHeader.messageSetting')}}</a>
                  <a href="javascript:;" @click="openTab('settingMessageChannel')">{{$t('frameHeader.channelSetting')}}</a>
                </div>
              </el-popover>
              <!-- 客服状态-start -->
              <CustomerServiceStatus
                v-if="showCustomerServiceStatus&&imEnabled"
                :service-status="serviceStatus"
                :service-info="serviceInfo"
                :tip-visible="tipVisible"
                @changeServiceStatus="changeServiceStatus"
                @updateTipVisible="updateTipVisible"
              ></CustomerServiceStatus>
              <!-- 客服状态-end -->
              
              <!-- start 日历快捷入口 -->
              <el-popover
                v-if="isShowTodayCalendar"
                trigger="hover"
                :value="calendarPopperVisible"
                popper-class="calendar-panel-popper"
                placement="bottom-end"
                @input="calendarPopperVisibleToggle"
              >
              
                <button
                  type="button"
                  class="btn-text frame-header-btn frame-header-btn-bg today-calendar-button"
                  slot="reference"
									v-track="$track.formatParams('NAV_SCHEDULE')"
                >
                  <i class="iconfont icon-fdn-date" @click="onClickGoCalendarHandler"></i>
                  <!-- <span
                    class="notification-new"
                    v-show="isShowTodayCalendarNum"
                  >
                    {{ todayCalendarNumDisplayString }}
                  </span> -->
                </button>
                
                <div>
                  <calendar-today-view 
                    ref="CalendarTodayView" 
                    @hide="calendarPopperVisibleToggle"
                    @input="calendarNumChangeHandler"
                  />
                </div>
                
              </el-popover>
              <!-- end 日历快捷入口 -->
              
              <el-popover
                popper-class="help-user-feedback"
                v-model="userFeedbackPopperVisible"
                trigger="hover"
              >
                <button
                  type="button"
                  class="btn-text frame-header-btn frame-header-btn-bg"
                  id="userFeedbackGuide"
                  slot="reference"
                >
                  <i class="iconfont icon-question-circle"></i>
                </button>
                <div class="feedback-profile-item">
                  <a href="javascript:;" @click.prevent="openHelpDoc" v-track="$track.formatParams('NAV_HELP')">{{$t('system.frameView.helpWiki')}}</a>
                </div>
                <div class="feedback-profile-item">
                  <a href="javascript:;" @click.prevent="openUserFeedBack" v-track="$track.formatParams('NAV_FEEDBACK')">{{$t('system.frameView.userSuggestion')}}</a>
                </div>
                <div class="feedback-profile-item">
                  <a href="javascript:;" @click.prevent="openPrivacy" v-track="$track.formatParams('NAV_PRIVACY')">{{$t('system.frameView.securityAgreement')}}</a>
                </div>
                <div class="feedback-profile-item">
                  <a href="javascript:;" @click.prevent="openUpdateLog">{{$t('system.frameView.versionDesc')}}</a>
                </div>

              </el-popover>

              <!-- NEW专属客服 -->
              <el-popover
                popper-class="help-user-feedback z99"
                v-model="exclusiveCustomerServiceVisible"
                trigger="hover"
              >
                <button
                  type="button"
                  class="btn-text frame-header-btn frame-header-btn-bg"
                  slot="reference"
                >
                  <i class="iconfont iconfont icon-kefu1"></i>
                </button>
                <div class="feedback-profile-item" @click="openSaleManager">
                  <span  v-track="$track.formatParams('NAV_SERVICE')">{{ $t('system.frameView.belongCustomerService') }}</span>
                </div>
                <div v-if="exclusiveCsIM" class="feedback-profile-item" id="exclusiveCsChat" @click="showChatModal">
                  <span>{{ $t('common.base.onlineConsultation') }}</span>
                </div>
              </el-popover>

              <el-popover
                v-if="isWhiteList"
                trigger="click"
                v-model="exportPopperVisible"
                popper-class="export-panel-popper"
                placement="bottom-end"
                :width="600"
                @input="exportPopoverToggle"
              >
                <button
                  type="button"
                  :title="backgroundTaskTitle"
                  v-tooltip
                  class="btn-text frame-header-btn frame-header-btn-bg"
                  slot="reference"
									v-track="$track.formatParams('NAV_BACKGROUND_DOWNLOAD')"
                >
                  <i class="iconfont icon-cloud-download"></i>
                </button>
                <!-- start 导入导出下载 -->
                <import-and-export-view
                  ref="importExport"
                  :title="backgroundTaskTitle"
                  :source-list="exportList"
                  :total="total"
                  :export-popper-visible="exportPopperVisible"
                  @change="operationListChange"
                  @onChangeTips="onChangeTips"
                  @onSortMark="onSortMark"
                ></import-and-export-view>
                <!-- end 导入导出下载 -->
              </el-popover>
              <!--导出下载-->

              <div class="frame-header-btn-notice-content" @click="openNotificationCenter">
                <button type="button"
                        class="btn-text frame-header-btn frame-header-btn-bg notification-btn"
                        :class="notificationClassNames"
                        :title="$t('system.frameView.notesCenter')"
                        v-tooltip
									      v-track="$track.formatParams('NAV_NOTIFICATION_CENTER')">
                  <i class="iconfont icon-bell"></i>
                </button>
                <span
                  class="notification-new"
                  v-show="isShowNotificationNum"
                >
                  {{ notificationNumDisplayString }}
                </span>
              </div>

              <!-- 个人信息 -->
              <el-popover popper-class="user-profile-menu" trigger="click">
                <div
                  class="frame-user-profile"
                  slot="reference"
                  id="frame-user-profile-guide"
									v-track="$track.formatParams('NAV_USER_AVATAR')"
                  @click="onUserProfileClickHandler"
                >
                  <a
                    class="user-avatar"
                    href="javascript:;"
                  >
                    <img :src="userAvatar" />
                    <span
                      v-if="loginUser.state"
                      class="user-color-icon user-color-icon-mini"
                      :style="{ backgroundColor: userStateColor }"
                    ></span>
                  </a>
                  <i class="iconfont icon-nav-down user-profile-down"></i>
                </div>

                <div class="frame-user-profile frame-user-profile-popover">
                  <a class="user-avatar" href="javascript:;">
                    <img :src="userAvatar" />
                  </a>
                  <div class="user-info">
                    <h4>
                      <template v-if="isOpenData">
                        <open-data ref="openDataRef" type="userName" :openid="loginUser.staffId"></open-data>
                      </template>
                      <template v-else>{{ loginUser.displayName }}</template>
                    </h4>
                    <p>
                      <!-- <span v-if="isProviderSign" class="user-peugeot">服务商</span> -->

                      <span
                        v-if="loginUser.state"
                        class="user-color-icon user-color-icon-mini"
                        :style="{ backgroundColor: userStateColor }"
                      ></span>
                      <span>{{ getUserWorkStateLabel(loginUser.state) }}</span>
                    </p>
                  </div>
                </div>

                <el-popover
                  placement="left-start"
                  popper-class="user-state-popper"
                  trigger="hover"
                  v-model="userStatePopperVisible"
                >
                  <div class="user-profile-item" slot="reference">
                    <i class="iconfont icon-user-status"></i>{{$t('system.frameView.workState')}}
                  </div>

                  <div class="user-state-panel">
                    <div
                      class="user-profile-item user-state-item"
                      v-for="(color, state) in userStateMap"
                      :key="state"
                      @click="chooseUserState(state)"
                    >
                      <span class="user-color-icon" :style="{ backgroundColor: color }"></span>
                      <span>{{ getUserWorkStateLabel(state) }}</span>
                    </div>
                  </div>
                </el-popover>

                <div class="user-profile-item">
                  <span @click.prevent.self="openUserView">
                    <i class="iconfont icon-people"></i>{{$t('system.frameView.personCenter')}}
                  </span>
                </div>
                <el-popover
                  placement="left-start"
                  popper-class="user-state-popper"
                  trigger="hover"
                  v-model="languagePoperShow"
                  v-if="haveLanguage && allowSwitch"
                >
                  <div class="user-profile-item" slot="reference">
                    <i class="iconfont icon-earth"></i>{{$t('system.frameView.language')}}
                  </div>
                  <div class="user-state-panel">
                    <div
                    :class="[$i18n.locale == item.languageKey ? 'language-choosed' : '', 'user-profile-item user-state-item']"
                      v-for="(item, index) in systemLanguageList"
                      :key="index"
                      @click="changeLanguage(item)"
                    >
                      <span>{{ item.languageValue }}</span>
                      <i v-if="$i18n.locale == item.languageKey" class="iconfont icon-check"></i>
                    </div>
                  </div>
                </el-popover>
                <el-popover
                  placement="left-start"
                  popper-class="user-state-popper"
                  trigger="hover"
                  v-model="tablePoperShow"
                >
                  <template #reference>
                    <div class="user-profile-item">
                      <i class="iconfont icon-biaoge"></i>{{$t('system.frameView.tableDisplay')}}
                    </div>
                  </template>
                  <div class="user-state-panel">
                    <div
                      :class="[tableDisplay === item.value ? 'language-choosed' : '', 'user-profile-item', 'user-state-item']"
                      v-for="(item, index) in systemTableList"
                      :key="index"
                      @click="changeTable(item)"
                    >
                      <span class="table-item">
                        <svg class="icon svg-icon mar-r-4" aria-hidden="true" width="16px" height="16px">
                          <use :xlink:href="'#' + item.icon"></use>
                        </svg>
                        <span>{{ item.name }}</span>
                      </span>
                      <i v-if="tableDisplay === item.value" class="iconfont icon-check"></i>
                    </div>
                  </div>
                </el-popover>
                <div class="user-profile-item" v-if="tenantInform && tenantInform.isMulti">
                  <a @click.prevent.self="openUserEnterprise">
                    <i class="iconfont icon-qiehuan1"></i>{{$t('system.frameView.changeTenant')}}
                  </a>
                </div>

                <div v-if="!isInWxWork && isShowLogout" class="user-profile-item logout">
                  <a href="javascript:;" @click.prevent="logout">
                    <i class="iconfont icon-logout"></i>
                    {{ isInDingTalk ? $t('system.frameView.cancellation') : $t('system.frameView.quit') }}
                  </a>
                </div>
              </el-popover>
            </div>
          </div>

        </header>

        <div class="frame-main">
          <div class="frame-tab-content">
            <div
              class="frame-tab-window"
              v-for="tab in frameTabs"
              :key="`${tab.id}`"
              v-show="tab.show"
            >
              <iframe
                :id="`frame_tab_${tab.id}`"
                :fromid="tab.fromId"
                :data-id="tab.id"
                :src="tab.url"
                allow="geolocation; microphone; camera; midi; encrypted-media;"
                @load="updateFrameTab($event, tab)"
                allowfullscreen
              />
            </div>
          </div>
        </div>
      </div>
      <!-- 隐私弹框 暂时隐藏后续迁移至账号登录页面 -->
      <!-- <privacy/> -->
      <version
        :version="releaseVersion"
        v-if="loadedEdition && !systemPopupShow"
        :edition="shbEdition"
        @showSystemPopup="showSystemPopup = false"
      />
      <!--start 系统弹窗 -->
      <system-popup :system-data.sync="systemData" v-if="loadedSystemModal" @closeSystemPopup="closeSystemPopup" />
      <!--end 系统弹窗 -->
      <sale-manager
        :service-group-url="initData.serviceGroupUrl"
        :qrcode="initData.saleManagerQRCode"
        :qrcode-url="initData.saleManagerGroupQRCode"
        :show.sync="saleManagerShow"
      />
      <notification-center
        ref="notification"
        :info="notificationInfo"
        :all-count="notification.count"
        @clearNum="clearNum"
        @ConversationSum="ConversationSum"
        @getNum="getNum"
        :is-show-notice="isShowNotice"
      ></notification-center>
      <!-- 标签栏改造需求 不需要tab右键菜单 -->
      <!-- <base-context-menu for=".frame-tabs-list" :menu-render="menuRender" @command="closeTabHandler" :collapse="collapse" ref="contextMenuRef"></base-context-menu> -->
    </div>
    <!-- start 用户向导 -->
    <user-guide ref="userGuideView" @closeUserGuide="closeUserGuide"></user-guide>
    <!-- end 用户向导 -->

    <!--start 切换企业 -->
    <switchcompanies-dialog
      ref="switchcompaniesToast"
      @handleClose="handleClose"
      v-if="switchcompaniesState"
      @refresh="refresh"
      :tenant-inform="tenantInform"
    ></switchcompanies-dialog>
    <!--end 切换企业 -->

    <!-- 多端企业切换 -->
    <div id="user-switch-companies-tour"></div>
    <!-- 多端修改密码 -->
    <div id="edit-pwd-tour"></div>

    <!--start 提醒修改密码 -->
    <!-- <v-tour v-if="showModifyPwdTour" name="modifyPwdTour" class="modify-pwd-tour" :steps="modifyPwdSteps">
      <template slot-scope="tour">
        <transition name="fade">
          <template v-for="(step, index) of tour.steps">
            <v-step
              v-if="tour.currentStep === index"
              :key="index"
              :step="step"
              :stop="tour.stop"
              :labels="tour.labels"
            >
              <template>
                <div slot="actions" class="option-btns">
                  <button @click="stopModifyPwdStep" class="btn btn-transfer">{{$t('common.base.ok')}}</button>
                </div>
              </template>
            </v-step>
          </template>
        </transition>
      </template>
    </v-tour> -->
    <!--end 提醒修改密码 -->

    <!-- start 日程管理需求-日程初始化设置提醒 -->
    <el-dialog
      :title="$t('system.frameView.planTimePop.title')"
      class="planningTimePop"
      :visible.sync="planningTimeDialog"
      width="672px"
    >
      <div class="pop_main">
        <h4>{{$t('system.frameView.planTimePop.des1')}}</h4>
        <div>
          <p>
            <span>{{$t('system.frameView.planTimePop.des2')}}</span>
            <span class="color1">{{$t('system.frameView.planTimePop.des3')}}</span>
            <span>{{$t('system.frameView.planTimePop.des4')}}</span>
            <span class="color1">{{$t('system.frameView.planTimePop.des5')}}</span>
            <span>{{$t('system.frameView.planTimePop.des6')}}</span>
            <span class="color1">{{$t('system.frameView.planTimePop.des7')}}</span>
            <span>{{$t('system.frameView.planTimePop.des8')}}</span>
            <span class="color1">{{$t('system.frameView.planTimePop.des9')}}</span>
            <span>{{$t('system.frameView.planTimePop.des10')}}</span>
          </p>
          <img :src="ptOptimize" :alt="$t('system.frameView.planTimePop.des13')" />
          <p class="p_Medium">{{$t('system.frameView.planTimePop.des11')}}</p>
          <p class="color1">{{$t('system.frameView.planTimePop.des12')}}</p>

          <el-radio-group v-model="planTimeTypeCode">
            <el-radio :label="1">{{$t('system.frameView.planTimePop.des7')}}</el-radio>
            <el-radio :label="2">{{$t('system.frameView.planTimePop.des8')}}</el-radio>
          </el-radio-group>
          <p>{{$t('system.frameView.planTimePop.des14')}}</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <base-button
          type="primary"
          @event="planningTime"
          :disabled="planTimeTypeCode ? false : true"
        >{{$t('common.base.confirm')}}</base-button>
      </div>
    </el-dialog>

    <!-- <el-dialog
      title="提示"
      :visible.sync="deleteDialog">
      <span>是否删除视图？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialog = false">取 消</el-button>
        <el-button type="primary" @click="deleteDialogConfirm">确 定</el-button>
      </span>
    </el-dialog> -->
    <!-- end 日程管理需求-日程初始化设置提醒 -->

    <!--start 用户意见反馈   -->
    <create-feed-back ref="createFeedback" :init-data="initData" @searchFeedBack="openFeedBackList"></create-feed-back>
    <feed-back-list ref="feedbackList" @createFeedback="openUserFeedBack"></feed-back-list>
    <!--end 用户意见反馈   -->

    <document-quote :visible.sync="documentQuoteShow" @choose="handleChooseDocument"></document-quote>
    <!--start 全局websocket -->
    <global-web-socket ref="GlobalWebSocketComponent" />
    <!--end 全局websocket -->

    <!-- start 消息中心通知 websocket -->
    <biz-web-socket
      :url="workbenchMessageWebsocketUrl"
      :on-connected="onNotificationConnected"
      :on-disconnected="onNotificationDisconnected"
      :on-error="onNotificationError"
      :on-message="onNotificationMessage"
    >
    </biz-web-socket>
    <!-- end 消息中心通知 websocket -->

    <!-- 菜单导航 -->
    <div id="menu-bar-guide"></div>
    <menu-bar-guide 
      v-if="showMenuBarGuide" 
      @openNotificationCenter="openNotificationCenter" 
      @handleCloseMenuBarGuide="handleCloseMenuBarGuide"
      @MenuBarGuideLeftClick="onMenuBarGuideLeftClick"
    >
    </menu-bar-guide>

    <!-- 内部协同IM导航 -->
    <div id="im-guide"></div>

    <!-- 专属客服导航 -->
    <div id="exclusive-customer-service-id"></div>

    <!-- 动态信息 -->
    <dynamic-info :visible.sync="dynamicInfoVisible" :user="loginUser"></dynamic-info>

    <!-- 在线客服iframe -->
    <OnlineChatModal ref="OnlineChatModal" v-if="isLoadChatModal" />
    
    <biz-chat-panel
      v-if="isChatGPTGray && isHaveGPTRobot"
      ref="BizChatPanel"
      :tenantId="tenantId"
      :gptRobot="gptRobot"
      :navCollapse="collapse"
    >
    </biz-chat-panel>
    
    <transition name="el-fade-in-linear">
      <NewBlurGuide v-show="nowGuide === formWithMultipleColumnsStashKey" @close="closeBlurGuide"></NewBlurGuide>
    </transition>
    
    <!-- start 异地登录提醒弹窗 -->
    <OffSiteLoginDialog ref="OffSiteLoginDialog" />
    <!-- end 异地登录提醒弹窗 -->
    
  </div>
</template>

<script>
import OnlineChatModal from '@src/modules/system/frame/component/OnlineChatModal.vue'
import { provide } from 'vue'
import * as CallCenterApi from '@src/api/CallCenterApi';
import * as SmartPlanApi from '@src/modules/smartPlan/api/index.js'
import { judgeUpdatePassWord } from '@src/api/UserCenterApi';
import { config, getReportAuth } from '@src/api/ReportApi.ts';
import * as GuideApi from '@src/api/GuideApi';
import { getRootWindowInitData } from '@src/util/window'
import * as ImApi from '@src/api/ImApi';
import platform from '@src/platform';
import http, { downloadByhref } from '@src/util/http';
import { safeNewDate } from '@src/util/time';
import FrameManager from './FrameManager';
import MenuBarGuide from './component/MenuBarGuide.vue';
import FrameTab from './component/FrameTab.vue';
import FrameTabGroup from './component/FrameTabGroup.vue';
import FrameNav from './component/FrameNav.vue';
import Version from './component/Version.vue';
import SystemPopup from './component/SystemPopup.vue';
import Privacy from './component/Privacy.vue';
import SaleManager from './component/SaleManager.vue';
import UserGuide from './component/UserGuide.vue';
import switchCompaniesDialog from './component/switchCompaniesDialog.vue';
import CreateFeedBackDialog from './component/userFeedback/CreateFeedBackDialog.vue';
import FeedBackListDialog from './component/userFeedback/FeedBackListDialog.vue';
import DocumentQuote from '@src/modules/repository/document/list/component/Quote.vue'
import GlobalWebSocket from './component/globalWebSocket/index.vue';
import ImportAndExport from './component/ImportAndExport.vue';
import OffSiteLoginDialog from './component/OffSiteLoginDialog';

import { getOssUrl, getLocalesOssUrl } from '@src/util/assets'
const DefaultHead = getOssUrl('/avatar.png')
const ptOptimize = getLocalesOssUrl('/pt_optimize.png');
import NotificationCenter from './component/NotificationCenter.vue';
import * as NotificationApi from '@src/api/NotificationApi';
import { userCenterLogOut } from '@src/util/userCenter';
import * as SettingApi from '@src/api/SettingApi.ts';
import DynamicInfo from './component/DynamicInfo.vue';

import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'
import WeiXinApplyTrailFeature from '@src/modules/system/frame/component/WeiXinApplyTrailFeature/WeiXinApplyTrailFeature.tsx';
import LarkApplyTrailFeature from '@src/modules/system/frame/component/LarkApplyTrailFeature/trail.vue';
import { useRole } from '@hooks/useRole.ts'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import CustomerServiceStatus from './component/CustomerServiceStatus'
import callCenter from './component/callCenter.vue'
import PersonalVersionOpeningGuide from '@src/modules/system/frame/component/PersonalVersionOpeningGuide.vue'
import { setThemeClass } from '@src/util/theme.ts';
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
import CallCenterZhiChi from '@src/modules/system/frame/component/CallCenterZhiChi'
import CallCenterTianRun from '@src/modules/system/frame/component/CallCenterTianRun'

import { getUserGuideStorageBase, setUserGuideStorageBase } from 'src/util/guideStorage.ts';
import FrameNotificationMixin from '@src/mixins/frameNotificationMixin'
import draggable from 'vuedraggable'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import { storageSet, storageGet, storageRemove, sessionStorageSet } from '@src/util/storageV2';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform' 
import { addClass, removeClass, getRootWindow } from '@src/util/dom';
import { SHBProductLineEnum } from "@shb-lib/tenant"

import newTaskGuideStore from '@src/component/guide/taskV2Store';
import newProductGuideStore from '@src/component/guide/productV2Store';
import { pageEventList,
  pageEventOrderList,
  pageCustomerList,
  pageCallCenterStage,
  pageTaskList,
  pageSparepartApply,
  pageLinkcOrderList, 
  pageTaskAuditList,
  pageTaskReviewList,
  pageSparepartStock } from 'pub-bbx-global/pageType/dist';

import ExpressEntrance from './component/ExpressEntrance/index.vue'

import CalendarTodayView from '@src/modules/system/frame/component/CalendarTodayView.vue'

import { openTabCalendar, closeTabCalendar, openTabForEventView, openTabForTaskView } from '@src/util/business/openTab'
import * as UserCardApi from '@src/api/UserCard'
import { useLoadLanguage } from '@hooks/useLocale'
import i18n from '@src/locales'
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import { UserWorkStateLabelEnum } from '@model/enum/LabelEnum'
import { getSystemLanguageList, setSystemLanguage, fetchCurrencyList } from '@src/api/SystemApi.ts'
import { getAllGrayInfo } from '@src/util/grayInfo';
import { getWatermaskStyle } from '@src/util/watermark'
/* service */ 
import { isSystemAdmin } from '@service/RoleService.ts'

import { larkPopDisplay } from '@src/api/CommonApi'
/* api */
import { getRobotList } from '@src/api/AIApi'
import { creatServerCachApi, getServerCachApi } from '@src/api/GuideApi'
import { debounce } from 'lodash'
/* util */
import { openDingtalkAuth } from "pub-bbx-utils"
import { changeTableStyle } from '@src/util/tableStyle'

const AllFormBuilderCellStorageKey = 'AllFormBuilderCellStorageKey'
const AllViewLayoutStorageKey = 'AllViewLayoutStorageKey'

import { isRobotSystem, isRobotEnabled } from '@src/modules/setting/gpt/utils'

/* hooks */
import { useFetchSettingGPTQuestionDelete } from '@gpt/hooks'

const GuideStoreObj = {
  ...newTaskGuideStore,
  ...newProductGuideStore
};
const NOTIFICATION_TIME = 1000 * 60 * 10;

const EXCLUSIVE_CUSTOMER_SERVICE_GUIDE_ID = 'exclusive-customer-service-id'
const SMART_PLAN_GUIDE = 'smart-plan-guide'
const SMART_PLAN_TAB = 'M_SMART_PLAN'

const tabMap = {
  customerServiceStatus_list: {
    title: i18n.t('frameHeader.tabMap.seatMonitoring'),
    url: '/security/roleService/view',
  },
  report1: {
    title: i18n.t('common.pageTitle.pageStatsBusiness'),
    url: '/stats/business?type=mtbt',
  },
  report2: {
    title: i18n.t('frameHeader.tabMap.costClassification'),
    url: '/stats/business?type=service_type',
  },
  report3: {
    title: i18n.t('frameHeader.tabMap.costStatistics'),
    url: '/stats/business?type=cost_stat',
  },
  report4: {
    title: i18n.t('frameHeader.tabMap.rateOfProduction'),
    url: '/stats/business?type=work_hours',
  },
  report5: {
    title: i18n.t('frameHeader.tabMap.faultStatistics'),
    url: '/stats/business?type=product_fault',
  },
  report6:{
    title: i18n.t('frameHeader.tabMap.personnelPerformance'),
    url:'/stats/business?type=personnel_performance'
  },
  report7:{
    title: i18n.t('frameHeader.tabMap.personnelCalendar'),
    url:'/stats/calendar?type=personnel_performance_calendar'
  },
  archive_view: {
    title: i18n.t('common.pageTitle.pageTaskArchiveList'),
    url: '/task/view/0bd6681a-dbd7-11ec-95dc-00163e304a25',
  },
  demo: {
    url: '/demo',
    title: 'demo',
  },
  calendar: {
    title:  i18n.t('common.pageTitle.pageSchedule'),
    url: '/calendar',
  },
  department_view: {
    title: i18n.t('frameHeader.tabMap.organizationChart'),
    url: '/security/department/view'
  },
  dept_view: {
    title: i18n.t('frameHeader.tabMap.organizationChart'),
    url: '/security/dept/view'
  },
  portal_setting: {
    title: i18n.t('common.pageTitle.pagePortal'),
    url: '/portal/setting',
  },
  portal: {
    title: i18n.t('common.pageTitle.pagePortal'),
    url: '/portal',
  },
  portal_config: {
    title: i18n.t('common.pageTitle.pagePortal'),
    url: '/portal/portal_config',
  },
  role_view: {
    title: i18n.t('common.pageTitle.pageSecurityRoleView'),
    url: '/security/role/view',
  },
  serviceProvider_view: {
    title: i18n.t('common.pageTitle.pageServiceManage'),
    url: '/security/serviceProvider',
  },
  productQrcode: {
    title: i18n.t('common.pageTitle.pageProductQrcode'),
    url: '/product/qrcode',
  },
  customer_tag: {
    title: i18n.t('customer.tagSetting.title'),
    url: '/setting/customer/tag',
  },
  intelligenceReport: {
    title: i18n.t('common.pageTitle.pageManagementReport'),
    url: '/stats/intelligenceReport/charts?chartName=average-response-time',
  },
  M_SMART_PLAN: {
    title: i18n.t('smartPlan.title'),
    url: '/smart/plan/list'
  },
  user_view: {
    title: i18n.t('common.pageTitle.pageSecurityUserView'),
    url: '/security/user/view/1bb20dad-ae62-11ec-8999-00163f00409a',
  },
  subManage: {
    title: i18n.t('frameHeader.informManage'),
    url: '/setting/message/subManage',
  },
  smsMessage: {
    title: i18n.t('common.pageTitle.pageSettingSmsmessage'),
    url: '/setting/message/smsMessage',
  },
  messageSetting: {
    title: i18n.t('common.pageTitle.pageSettingMessage'),
    url: '/setting/message',
  },  
  settingMessageChannel: {
    title: i18n.t('frameHeader.channelSetting'),
    url: '/setting/message/channel',
  },
  taskTest: {
    title: 'AI NL2Params',
    url: '/setting/gpt/test',
  },
  pageSparepartStock:{
    title: i18n.t('part.components.partStock.text2'),
    url:pageSparepartStock.url,
    doSome:(vue)=>{
      const { id, title, url } = pageSparepartStock;
      let data = {
        filterData:{
          isMissingPart:1
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageSparepartStock',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  pageLinkcOrderList:{
    title: i18n.t('common.pageTitle.pageLinkcOrderList'),
    url:pageLinkcOrderList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageLinkcOrderList;
      let data = {
        filterData:{moreConditions: {
          stateList: [1]
        }}
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageLinkcOrderList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  pageTaskAuditList:{
    title: i18n.t('common.pageTitle.pageTaskAuditList'),
    url:pageTaskAuditList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageTaskAuditList;
      let data = {
        filterData:{
          balanceConfirmChangedHandler:'BalanceConfirm'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageTaskAuditList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  pageTaskReviewList:{
    title: i18n.t('frameHeader.tabMap.returnVisitToWorkOrder'),
    url:pageTaskReviewList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageTaskReviewList;
      let data = {
        filterData:{
          toggleReviewValue:'Reviewed'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageTaskReviewList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  customerList:{
    title: i18n.t('frameHeader.tabMap.customersList'),
    url:pageCustomerList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageCustomerList;
      let data = {
        filterData:{
          createView:'synergies'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageCustomerList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  eventList:{
    title: i18n.t('frameHeader.tabMap.eventist'),
    url:pageEventList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageEventList;
      let data = {
        filterData:{
          state:'allFinished'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageEventList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  eventOrderList:{
    title: i18n.t('common.pageTitle.pageEventOrderList'),
    url:pageEventOrderList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageEventOrderList; 
      let data = {
        filterData:{
          state:'allFinished'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageEventOrderList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    },
  },
  callCenterStage:{
    title:pageCallCenterStage.title,
    url:pageCallCenterStage.url,
  },
  taskList:{
    title: i18n.t('common.pageTitle.pageTaskList'),
    url:pageTaskList.url,
    doSome:(vue)=>{
      const { id, title, url } = pageTaskList; 
      let data = {
        filterData:{
          state:'processingId'
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageTaskList',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  sparepartApply:{
    title: i18n.t('common.pageTitle.pageSparepartApply'),
    url:pageSparepartApply.url,
    doSome:(vue)=>{
      const isDev = process.env.NODE_ENV !== 'production';
      const { id, title, url, type } = pageSparepartApply; 
      let data = {
        filterData:{
          state:['solved']
        }
      }
      platform.openTab({
        isFasterPage:{
          pageType:'pageSparepartApply',
          pageData:data
        },
        id,
        title,
        url,
        reload: true,
      })
    }
  },
  
}

import NewBlurGuide from '@src/component/compomentV2/newBlurGuide/index.vue'
import { useSataeFrameGuide, formWithMultipleColumnsStashKey } from '@src/modules/system/frame/store'

export default {
  mixins: [FrameManager, ThemeMixin, VersionMixin, FrameNotificationMixin],
  name: 'frame-view',
  // inject: ['initData'],
  props: {
    initData: {
      type: Object,
      default: null,
    },
  },
  setup (props) {
      provide('initData', props.initData)
      const { isSystemManager } = useRole()
      const {setLocale} = useLoadLanguage();
      
      const { fetchQuestionDelete } = useFetchSettingGPTQuestionDelete()
      
      const { nowGuide, activeGuide, reActiveGuide } = useSataeFrameGuide()

      function changeLanguage(lan){
        const { languageKey } = lan;
        setSystemLanguage({
          languageType:languageKey,
          deviceType:1
        }).then(res=>{
          if (res.code == 0 || res.status == 0) {
            this.$message.success(res.message);
            setLocale(languageKey)
          } else {
            throw res
          }
        }).catch(err=>{
          console.warn('http erro',err);
        }).finally(()=>{
        })
        
      }
      window.activeGuide = activeGuide
      window.reActiveGuide = reActiveGuide
      function closeBlurGuide(){
        reActiveGuide(formWithMultipleColumnsStashKey)
      }
      
      return { 
        fetchQuestionDelete,
        isSystemManager,
        changeLanguage,
        nowGuide,
        activeGuide,
        reActiveGuide,
        formWithMultipleColumnsStashKey,
        closeBlurGuide
      }
    },
  data () {
    return {
      allowSwitch: true,
      isLoadChatModal:false,
      systemLanguageList: [],
      languagePoperShow:false,
      systemTableList: [
        { name: i18n.t('system.frameView.truncation'), value: 'Truncation', icon: 'icon-zidongjieduan' },
        { name: i18n.t('system.frameView.wrap'), value: 'AutoWrap', icon: 'icon-zidonghuanhang' },
      ],
      tableDisplay: localStorage.getItem('tableDisplay') || 'Truncation',
      tablePoperShow: false,
      callCenterType: -1, // 0:中通天鸿 1:智齿 2:七鱼 3:天润
      isShowLogout: false,
      showUserFeedbackGuide: true,
      showSystemPopup: true,
      tabMap,
      ConversationNum: 0,
      isOpenData: false,
      isInDingTalk: platform.inDingTalk,
      isChecked: platform.isChecked,
      tenantInform: {},
      switchcompaniesState: false,
      notificationInfo: {},
      notification: {
        count: 0,
      },
      systemMsg: '',
      notificationShow: false,
      notificationStyle: {},
      loginUser: this.initData.user || {}, // 当前登录的用户
      profilePopperVisible: false,
      userStatePopperVisible: false,
      saleManagerShow: false, // 是否显示专属客服
      exportPopperVisible: false,

      collapse: false,

      // 导出相关变量
      exportPanelShow: false,
      exportTimer: null,
      exportList: [],
      operationList: [],

      // 后台任务
      backgroundTaskTitle: i18n.t('frame.backgroundTask.title'),
      navBarMenus: [],
      moreMenus: [],
      showNavBar: false,
      loadedEdition: false,
      loadedSystemPopup: false,
      systemData: [],
      shbEdition: 1,
      taskListIds: ['M_TASK_ALL'],
      confirmSetting: this.initData.confirmSetting, // 通过工单设置升级为3.0后需隐藏返回旧版按钮
      // 日程管理需求-日程初始化设置提醒
      ptOptimize,
      planningTimeDialog: false,
      pending: false,
      planTimeTypeCode: '',
      isTalking: false,
      sortMark: 0,
      total: 0,
      themeClass: 'theme-primary',
      isProviderSign: false, // 当前组织名称
      checkExportsLoading: false, // 导出列表查询状态
      rootWindowInitData: getRootWindowInitData(),
      trailClosed: false,
      userFeedbackShow: false, // 意见反馈是否显示
      userFeedbackPopperVisible: false, //
      exclusiveCustomerServiceVisible:false, // 专属客户是否显示
      remarkDesignModal: false, // 服务备注表单设置器
      documentQuoteShow: false, // 知识库引用弹框
      dpcumentQuoteFrame: null, // 知识库引用
      serviceStatus: '',
      serviceInfo: {}, // 在线客服信息
      showCustomerServiceStatus: false,
      phoneStatusMap: {
        1: {
          color: '#00C853',
          text: i18n.t('common.callCenter.phoneStatus.work'),
        },
        0: {
          color: '#8C8C8C',
          text: i18n.t('common.callCenter.phoneStatus.rest'),
        },
      },
      feedbackGuideDom: null,
      userGuideStroage:null,
      im_isOpen:0,
      frameContextMenuVisible: false,
      frameContextMenus: [],
      dragOptions: {
        animation: 380, 
        ghostClass: 'ghost'
      },
      showModifyPwdTour: true,
      imEnabled:false, // 在线客服设置总开关状态
      systemPopupShow:true,
      calendarPopperVisible: false,
      todayCalendarNum: 0,
      tabMap,
      tenantName:'众联成业',
      showLarkTrailTop:false,
      tipVisible: false,
      grayAuth: null,
      robotList: [],
      watermaskContent: '',
      getWatermaskStyle,
      defaultActive: '',
      allFormBuilderCell: 1,
      allViewLayout: {
        baseLayout: 2,
			  formCellCount: 1,
      },
      exportAutoDownData: {},
      timer: null,
      counter: 0,
      isSkipAllGuide: false,
    };
  },
  computed: {
    /**
     * @description 是否是个人版本
     * -- 个人版本需要显示引导提示
     * @return {Boolean}
     */
    isPersonalVersion() {
      return this.personalConfigVO.personal === true && this.isInDingTalk
    },
    personalConfigVO(){
      return this.initData ? this.initData?.personalConfigVO || {} : {}
    },
    logoImg() {
      return this.logoUrl;
    },
    tenantType () {
      return this.initData.tenantType;
    },
    isWhiteList () {
      if (this.tenantType == 2) {
        return getRootWindowInitData().WHITE_LIST
      }
      return true
    },
    isShowUserGuide () {
      return getRootWindowInitData().isShowUserGuide
    },
    loadedSystemModal () {
      let res = this.loadedSystemPopup;
      return res;
    },
    /** 是否显示devtool */
    showDevTool () {
      if (process.env.NODE_ENV !== 'production') return true;
      return false
    },
    /** 用户工作状态颜色配置 */
    userStateMap () {
      return this.initData.userStateMap || {};
    },
    /** 用户工作状态颜色 */
    userStateColor () {
      let state = this.loginUser.state;
      return this.userStateMap[state];
    },
    /** 用户头像 */
    userAvatar () {
      return this.loginUser.head || DefaultHead;
    },
    releaseVersion () {
      return (
        (this.initData.releaseVersion
          && this.initData.releaseVersion
            .toLocaleLowerCase()
            .replace('vip', '')
            .replace('version', '')
        )
        || ''
      );
    },
    /* 是否是系统管理员 */
    isSystemAdmin () {
      let roles = this.loginUser.roles || [];
      return roles.some(role => isSystemAdmin(role));
    },
    isInWxWork () {
      // 判断是否在企业微信客户端里
      return window.navigator.userAgent.toLowerCase().indexOf('wxwork') > 0
    },
    // 是否为企业微信成员授权
    isAuthMode () {
      return this.initData?.authMode
    },
    isShowTrail () {
      return useRole().isAdmin && this.rootWindowInitData.tenantType == 2 && !this.rootWindowInitData?.isApplyGray && this.rootWindowInitData.isPay !== 1 && !this.notificationShow && !this.trailClosed
    },
    // 是否显示飞书
    isShowLarkTrail () {
      return this.showLarkTrailTop && this.localLarkTrailNotification == 'true' && this.rootWindowInitData.tenantType == 4 && this.rootWindowInitData.isPay !== 1 && !this.notificationShow && !this.trailClosed
    },
    // 本地存储飞书本次登录关闭顶部留资通知
    localLarkTrailNotification(){
      return localStorage.getItem('lark_trail') || false
    },
    isShowTodayCalendar() {
      return this.initData?.calendar
    },
    isShowNotice() {
      return this.initData?.notice
    },
    isShowTodayCalendarNum() {
      return this.todayCalendarNum > 0
    },
    todayCalendarNumDisplayString() {
      return this.todayCalendarNum > 99 ? '99+' : this.todayCalendarNum
    },
    showMenuBarGuide(){
      
      if (this.isSkipAllGuide) {
        return false
      }
      
      let res = false;
      if(this.initData.user) {
        if(this.initData.user.firstLogin == 2) {
          // 老用户 
          // 1.如果有系统通知并且有版本更新，     系统弹窗通知-->系统更新通知-->三级菜单设置引导
          // 2.如果有系统通知并且没有版本更新，   系统弹窗通知-->三级菜单设置引导
          // 3.如果没有系统通知并且有版本更新，   系统更新通知-->三级菜单设置引导
          // 4.如果没有系统通知并且没有版本更新， 三级菜单设置引导
          res = (!this.loadedEdition || !this.showSystemPopup) && !this.systemPopupShow 
        } else {
          // 新用户 用户反馈显示之后显示菜单引导
          res = !this.showUserFeedbackGuide;
        }
      }
      return res;
    },
    /**
     * @des 多语的灰度判断
     */
    haveLanguage(){
      return !!(this.grayAuth && this.grayAuth[GrayFunctionEnum.INTERNATIONAL])
    },
    exclusiveCsIM(){
      // 专属在线客服灰度
      return this.grayAuth?.exclusiveCsIM
    },
    smartPlanGray() {
      return this.grayAuth?.SMART_PLAN
    },
    tenantId () {
      return this.rootWindowInitData?.user?.tenantId;
    },
    isChatGPTGray() {
      return this.grayAuth?.chat_GPT
    },
    gptRobot() {
      return this.robotList.find((item) => {
        return isRobotSystem(item) && isRobotEnabled(item)
      })
    },
    isHaveGPTRobot() {
      return Boolean(this.gptRobot)
    },
  },
  methods: {
    // 获取用户工单状态多语言label
    getUserWorkStateLabel(name) {
      return UserWorkStateLabelEnum[name] || name
    },
    getInitAuth () {
      this.getShbEdition()
      this.getBasicEditionAuth()
      this.getGrayAuth()
      // 使用新语言接口
      // this.getLanguages()
    },
    serviceOffWork() {
      this.$nextTick(() => {
        this.tipVisible = true;
      })
    },
    // 升级到智能计划
    upgradeToSmartPlan() {
      SmartPlanApi.upgradeToSmartPlan().then(res => {
        const planTaskFrame = this.findTab('M_SCHEDULE_TASK')
        // 当计划任务页面存在时
        if (planTaskFrame) {
          this.framePostMessage(this.findTab('M_SCHEDULE_TASK'), {
            action: 'upgradeToSmartPlanRes',
            data: res,
          });
        }
        if (res.succ) {
          // 当计划任务页面不显示时提示
          if (!planTaskFrame || !planTaskFrame.show) {
            let notification = this.$notify({
              title: this.$t('smartPlan.upgrade.text8'),
              dangerouslyUseHTMLString: true,
              customClass: 'upgrade-success-notification',
              message: `
                <div class="upgrade-success-content">
                  <div class="upgrade-success-tip mar-b-16">${this.$t('smartPlan.upgrade.text9')}</div>
                  <div class="upgrade-success-button">
                    <button id="upgrade-success-refreshNow" type="button" class="btn btn-primary mar-r-12">${this.$t('smartPlan.upgrade.refreshNow')}</button>
                    <button id="upgrade-success-wait" type="button" class="btn btn-ghost">${this.$t('smartPlan.upgrade.wait')}</button>
                  </div>
                </div>
              `,
              duration: 0,
              type: 'success',
            })
            // 按钮操作处理
            document.getElementById('upgrade-success-refreshNow').addEventListener('click', () => {
              window.location.reload()
            })
            document.getElementById('upgrade-success-wait').addEventListener('click', () => {
              notification.close()
            })
          }
        } else {
          this.$message.error(this.$t('common.base.tip.operationFail'))
        }
      })
    },
    updateTipVisible(state = false) {
      this.tipVisible = state;
    },
    handlerTrailClose () {
      this.trailClosed = true
    },
    handlerLarkTrailClose(){
      this.trailClosed = true
      localStorage.setItem('lark_trail',false)
      localStorage.setItem('lark_login',false)
    },
    async getConfig () {
      const res = await config()
      sessionStorage.setItem('_init_data', JSON.stringify(res))
    },
    userFeedbackGuide () {
      let key = newProductGuideStore['USER_FEED_BACK']
      // 判断是否显示新手引导
      if ((this.initData.user && this.initData.user.firstLogin != 2 ) && this.userGuideStroage && this.userGuideStroage[key] && this.userGuideStroage[key].isComplete == 0) {
        this.feedbackGuideDom && this.feedbackGuideDom.$children[0].clearGuide()
        this.showUserFeedbackGuide = false;
      }
      else {
        try {
          if(this.initData.user && this.initData.user.firstLogin == 2 ){
            this.getSystemPopup();
            this.initIMGuide();
            return
          }
          this.$Guide([{
            domId: 'userFeedbackGuide',
            id: 'user-feed-back-guide',
            content: i18n.t('common.base.feedbackGuide.content'),
            stepTotalSetting:{
              finishBtn: i18n.t('common.base.ok'),
              leftBtn: i18n.t('common.base.skip'),
              needCover:true,
            }
          }], 0, '', (e) => {
            
            if (e.type == 'left') {
              this.skipAllGuide()
              return Promise.resolve()
            }

            return new Promise((resolve, reject) => {
              this.showUserFeedbackGuide = false;
              resolve();
            })
          }).create().then(vueDom => {
            if (vueDom) {
              setUserGuideStorageBase({
                userGuideList: [
                  {
                    type: key,
                    step: 1,
                    isComplete: 0
                  }
                ]
              }, this.userGuideStroage).then(res=>{
                this.userGuideStroage = res;
              });
              this.feedbackGuideDom = vueDom;
            }
          })
        } catch (error) {
          console.warn(error, 'error try catch');
        }
      }
    },
    // PC端获取在线客服的开通状态 data:0 未开通 1：开通
    async getImOpenState(){
      try {
        localStorage.setItem('im_isOpen', 0)
        const {code, data} = await ImApi.getImOpenState();
        if (code !== 0) return;
        localStorage.setItem('im_isOpen', data)
        if(data){
          this.im_isOpen = data
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    /**
     * 获取im initData
     * 用来判断灰度开关
     */
    async getImInitData () {
      // 因为机器人设置需要灰度
      // setting 页面再web项目中
      // 所以需要再这里获取 再存到localstorage里
      try {
        localStorage.setItem('im_initData', 0)
        const data = await SettingApi.getImConfig();
        localStorage.setItem('im_initData', JSON.stringify(data));
      } catch (error) {
        console.error('error', error);
      }
    },
    // 获取日程排班的坐班灰度
    async getSchedulingData() {
      try {
        localStorage.setItem('openScheduling', false)
        const data = await SettingApi.getSchedulingConfig();
        localStorage.setItem('openScheduling', JSON.stringify(data));
      } catch (error) {
        console.error('error', error);
      }
    },
    // 获取结算管理的灰度
    async getSettleData() {
      try {
        localStorage.setItem('openSettleManage', false)
        const data = await SettingApi.getSettleConfig();
        localStorage.setItem('openSettleManage', JSON.stringify(data));
      } catch (error) {
        console.error('error', error);
      }
    },

    // 人员卡片开关
    async getShowUserCard() {
      try {
        localStorage.setItem('showUserCard', false)
        const res = await UserCardApi.isShowUserCard();
        localStorage.setItem('showUserCard', res.data || false);
      } catch (error) {
        console.error('error', error);
      }
    },
    async checkBind(){
      try {
        if (this.tenantType == 2) {
          // 企业微信第三方应用
          const { status, data = {} } = await http.post('/dd/check/qywx', {})
          if (status != 0) return
          if (data.isThird == 'true' && data.needInfo == 'true') {
            this.showWxBindDialog = true
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    // TODO 代码未使用
    async bindUserInfo () {
      this.$refs.bindFormRef.validate(async valid => {
        if (!valid) return
        this.pending = true;
        try {
          const { status, message = i18n.t('frameHeader.tabMap.retry') } = await http.post('/dd/qywx/updateInfo', this.bindForm, false)
          this.pending = false
          if (status != 0) return this.$platform.notification({
            title: i18n.t('common.base.tip.operationFail'),
            message,
            type: 'error',
          });
          this.showWxBindDialog = false
          this.$platform.notification({
            message: i18n.t('common.base.tip.bindSuccess'),
            type: 'success',
          });
          window.location.reload()
        } catch (error) {
          this.pending = false
          console.error(error)
        }
      })
    },
    // TODO 代码未使用 end

    onSortMark (sortMark,) {
      this.sortMark = sortMark
      this.checkExports();
    },
    onChangeTips (type) {
      this.exportPopperVisible = true;
    },
    // 获取多租户信息
    async getTenantInform (isGuide = true) {
      try {
        const { data, success } = await SettingApi.getSwitchingCompanies();
        
        if (success) {
          this.tenantInform = data;
        }
        // 去除多租户切换租户引导
        // if (data?.isMulti && isGuide && success) {
        //   this.queryUserGuide('user-switch-companies-tour')
        // }
        
      } catch (error) {
        console.error(error);
      }
    },
    stopModifyPwdStep() {
      this.showModifyPwdTour = false

      const key = StorageKeyEnum.ModifyPWD
      storageSet(key, true);

      this.openUserView();
      // 更新定期修改密码的值isUpdatePassword为false
      judgeUpdatePassWord();
    },
    // 切换企业
    async openUserEnterprise () {
      
      this.switchcompaniesState = true;
      this.profilePopperVisible = false;
      
      this.getTenantInform(false)
      
      this.$nextTick(() => {
        this.$refs.switchcompaniesToast.openDialog();
        this.$refs.tenantInform = this.tenantInform;
      });
      
    },
    handleClose () {
      this.switchcompaniesState = false;
    },
    refresh () { },
    // 舍弃
    // updateSystemPopup () {
    //   this.showSystemPopup = true
    // },
    // menuRender (h, target) {
    //   this.$nextTick(()=>{
    //     if(this.frameContextMenuVisible) {
    //       this.frameContextMenuVisible = false;
    //     }
    //   })
    //   let menus = [
    //     <base-context-menu-item command="all">关闭全部标签</base-context-menu-item>,
    //     <base-context-menu-item command="other">关闭其它标签</base-context-menu-item>
    //   ];
    //   const tab = document.querySelector('.frame-tab-active');
    //   if (tab && tab.id != 'tab_HOME') {
    //     menus.unshift(
    //       <base-context-menu-item command="itself">关闭当前标签</base-context-menu-item>
    //     );
    //   }

    //   return menus;
    // },
    adjustOpenTab () {
      let tab = this.frameTabs.find((item) => item.show);
      this.adjustFrameTabs(tab);
    },
    openTab(item, type) {
      if(tabMap[item].doSome){
        return tabMap[item].doSome(this);
      }
      platform.openTab({
        id: item,
        title: tabMap[item].title,
        url: tabMap[item].url,
        reload: true,
      });
    },
    openEnumTab(){
      let params_ = openAccurateTab({
        type: "pageQualificationManagementView",
        params:'id=12'
      });
      console.log(params_, 'params_')
    },
    /** 选择用户状态 */
    async chooseUserState (state) {
      this.userStatePopperVisible = false;
      this.profilePopperVisible = false;
      try {
        let result = await http.post(
          '/security/user/updateState',
          { state },
          false
        );
        if (result.status == 0) {
          this.updateUserState(state);
          let iframe = document.getElementById('frame_tab_userCenter').contentWindow;
          iframe.postMessage({ state }, window.location.origin);
        } else {
          platform.alert(result.message);
        }
      } catch (error) {
        console.error(error);
      }
    },
    updateUserState (state) {
      this.$set(this.loginUser, 'state', state)
    },
    changeTable(item) {
      localStorage.setItem('tableDisplay', item.value);
      this.tableDisplay = item.value;
      // 获取所有的 iframe 元素
      const iframes = document.getElementsByTagName('iframe');

      for (let i = 0; i < iframes.length; i++) {
        try {
          // 向 iframe 发送消息以更改样式
          iframes[i].contentWindow.postMessage({action: 'changeTableStyle'}, '*');
        } catch (error) {
          console.error(error);
        }
      }
      // window.location.reload();
    },
    async logout () {
      if (await platform.confirm(i18n.t('common.base.tip.logout'))) {
        localStorage.removeItem('IS_CLICK_REMOVE_SERVICE_MANAGE_TIP')
        sessionStorage.removeItem('chatSortValue')
        // 用户中心退出登录
        userCenterLogOut()
      }
    },
    openHelpDoc (event) {
      let url;
      // 新版本帮助文档
      if(this.rootWindowInitData.cloudVersion) {
        const productLineList = this.rootWindowInitData.productLineList || []
        if (productLineList.includes(SHBProductLineEnum.BusinessServiceCloud)) {
          url = 'https://doc.shb.ltd/'
        } else {
          url = 'https://doc.shb.ltd/'
        }
      } else {
        url = 'https://doc.shb.ltd/'
      }
      platform.openLink(url);
      this.profilePopperVisible = false;
      this.userFeedbackPopperVisible = false;
    },
    openPrivacy() {
      // 新版本隐私协议
      let url = 'https://doc.shb.ltd/shb_dh7hof/ysxy.html';

      platform.openLink(url);
      this.profilePopperVisible = false;
      this.userFeedbackPopperVisible = false;
    },
    // 版本更新日志
    openUpdateLog() {
      let url;
      if(this.rootWindowInitData.cloudVersion) {
        const productLineList = this.rootWindowInitData.productLineList || []
        if (productLineList.includes(SHBProductLineEnum.BusinessServiceCloud)) {
          url = `https://doc.shb.ltd/shb_xwcs5n/${this.releaseVersion.replace(' ', '')}.html`
        } else {
          url = `https://doc.shb.ltd/shb_gnmf9i/${this.releaseVersion.replace(' ', '')}.html`
        }
      } else {
        url = `https://doc.shb.ltd/shb_xwcs5n/${this.releaseVersion.replace(' ', '')}.html`
      }
      platform.openLink(url);
      this.profilePopperVisible = false;
      this.userFeedbackPopperVisible = false;
    },
    goback (){
      history.go(-2);return false;
    },
    openUserView (event) {
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageMineView,
        key: this.loginUser?.userId || '',
        fromId
      })

      this.profilePopperVisible = false;
    },
    openSaleManager () {
      this.saleManagerShow = true;
      this.profilePopperVisible = false;
    },
    openNotificationCenter () {
      let notificationRef = this.$refs.notification

      if(!notificationRef) return;

      this.profilePopperVisible = false;

      let state = notificationRef.show

      if(state){
        notificationRef.handleHide();
        return
      }

      notificationRef.showComponent()
      
    },
    openUserFeedBack () {
      this.userFeedbackPopperVisible = false;
      this.$refs.createFeedback.openDialog();
    },
    openFeedBackList () {
      this.$refs.feedbackList.openDialog();
    },
    clearExportTimer () {
      if (this.exportTimer) {
        this.exportTimer = null
        clearTimeout(this.exportTimer);
      }
    },
    /** 检测是否有导出 */
    async checkExports (options = {}) {
      if (this.checkExportsLoading || this.exportTimer) return;
      this.clearExportTimer();
      this.checkExportsLoading = true;
      try {
        const params = {
          sortMark: this.sortMark
        }
        let { total, data } = (await http.post('/excels/getList', params));
        this.exportList = data;
        this.total = total;
        // 更新操作列表
        if (!Array.isArray(this.exportList)) this.exportList = [];
        // 更新操作列表
        this.operationList = this.operationList.filter((item) => {
          return (
            item.operate == 'cancel'
            || (item.operate == 'download'
              && this.exportList.some((exp) => exp.id == item.id))
          );
        });

        // 以下情况需要刷新列表
        // 1. 有为导出完成的文件
        // 2. 操作列表中仍有下载的文件
        const now = +safeNewDate();
        const oneDay = 24 * 60 * 60 * 1000;
        let autoFetchExportList = this.exportList.some((item) => {
          return (item.isFinished == 0 || item.isFinished == 4) && (now - item.createTime) < oneDay
        })
        // || this.operationList.some((item) => item.operate == 'download');

        // 如果不需要更新，清空定时器
        // if (!autoFetchExportList) {
        //   clearInterval(this.exportTimer);
        //   this.exportTimer = null;
        //   return;
        // }

        this.exportList.forEach(item => {
          // 获取需要自动下载的项
          const { id, isFinished, isDownload, finishTime } = item;

          /**
           * @desc  k:v对应值【1】初始化 【2】可以自动下载
           */
          // 1. mounted中初始化所有项
          if(options.init){
            this.exportAutoDownData[id] = 1;
          }else {
            // 2. 筛选出导出中和排队中的项 || 导出过快（在弹窗未打开就已经导出完成的，此项为被初始化过）
            if(isFinished == 0 || isFinished == 4 || (!this.exportAutoDownData[id] && isFinished == 1 && isDownload == 0)) {
              this.exportAutoDownData[id] = 2;
            }

            // 3. 完成自动下载
            if(this.exportAutoDownData[id] == 2 && isFinished == 1 && isDownload == 0 && finishTime) {
              this.$set(this.exportAutoDownData, id, 1)
              this.exportDownload(item);
              item.isDownload = 1;
            }
          }
        })

        // 如果需要更新,设置定时抓取数据
        // if (!this.exportTimer)
        //   this.exportTimer = setInterval(() => this.checkExports(), 5000);
        
        if (autoFetchExportList) {
          this.exportTimer = setTimeout(() => {
            this.exportTimer = null;
            // if (this.exportPopperVisible) {
              // 弹框开着时轮询
              this.checkExports();
            // }
          }, 5000);
        }
      } catch (error) {
        console.error('查询导出列表失败', error);
        // clearInterval(this.exportTimer);
        // this.exportTimer = null;
      } finally {
        this.checkExportsLoading = false;
      }
    },
    /* 导入导出操作列表变化 */
    operationListChange (list) {
      this.operationList = list;
      this.checkExports();
    },
    clearStorage () {
      localStorage.clear();
    },
    /** @deprecated */
    clearCachedIds () {
      let cachedKey = localStorage.getItem('cachedKey');
      let cachedKeyArray = [];

      if (cachedKey) cachedKeyArray = cachedKey.split(',');
      cachedKeyArray.forEach((key) => localStorage.setItem(key, []));
      localStorage.removeItem('cachedKey');
    },
    // popover manage
    exportPopoverToggle (visible) {
      // if (visible === this.exportPopperVisible) return; //
      this.exportPopperVisible = visible;
      if (visible) {
        this.profilePopperVisible = false;
        this.userStatePopperVisible = false;
        this.checkExports(); // 更新后台任务列表
      }
    },
    calendarPopperVisibleToggle(visible) {
      
      if (visible === this.calendarPopperVisible) return
      
      this.calendarPopperVisible = visible
      
      if (visible) {
        this.calendarTodayHandler()
      }
      
    },
    calendarNumChangeHandler(num) {
      this.todayCalendarNum = num
    },
    closeNotification () {
      this.notificationShow = false;
      sessionStorage.setItem(
        'shb_systemMsg',
        this.notificationInfo.msgSystem.id
      );
      // this.clearAnimation();
    },
    // 获取系统弹窗
    async getSystemPopup () {
      try {
        let info = await http.get('/api/app/outside/message/v1/getSysMsgAlert');
        if (info.status == 0 && info.data?.length > 0) {
          this.loadedSystemPopup = true;
          this.systemData = info.data;
          this.systemPopupShow = true;
        } else{
          this.systemPopupShow = false;
        }
        
      } catch (error) {
        console.error(error);
        this.systemPopupShow = false;
      }
    },
    // 获取系统消息，本地存储，超出滚动
    async getSystemMsg () {
      try {
        let info = await NotificationApi.newGetMessage();
        if (info.status == 0) {
          this.notificationInfo = info.data;
          this.notification.count = info.data.unReadTotalCount;
          let msgSystem = sessionStorage.getItem('shb_systemMsg');

          if (
            this.notificationInfo.lastMessage
            && (!msgSystem || msgSystem != this.notificationInfo.lastMessage.id)
          ) {
            this.notification.title = info.data.lastMessage.title;
            this.notificationShow = true;
            // this.setAnimation();
          } else {
            this.notification.title = null;
            this.notificationShow = false;
          }
        }
      } catch (error) {
        console.error(error);
      }
    },

    /**
     * TODO 新版本通知不需要滚动
     * 设置滚动动画
     */
    setAnimation () {
      this.$nextTick(() => {
        let textWidth = this.$refs.notificationText.offsetWidth;
        let infoWidth = this.$refs.notificationInfo.offsetWidth - 30;
        if (textWidth > infoWidth) {
          let time = this.notification.title.length / 4;
          this.$refs.notificationContent.style.animation = `text-scroll ${time}s linear infinite`;
        }
      });
    },
    /**
     * TODO 新版本通知不需要滚动
     * 删除滚动动画
     */
    clearAnimation () {
      this.$refs.notificationContent.style.animation = '';
    },

    /** 删除未读消息或消息已读后更新新通知数量 */
    clearNum (e) {
      if (e.count == -1) return (this.notification.count = 0);
      let count_ = this.notification.count - e.count;
      // 通知总数风险把控不把非正整数暴露给用户
      if (count_ < 0) {
        console.warn('通知消息总数为负数');
        count_ = 0;
      }
      count_ = Math.round(count_);
      this.notification.count = count_;
    },
    getNum () {
      this.getSystemMsg();
    },
    ConversationSum (num) {
      this.ConversationNum = num
    },
    // async resetGuide (path) {

    //   try {
    //     let res_ = await import(`@src/component/guide/${path}Store`);

    //     for (let key in res_) {
    //       localStorage.removeItem(res_[key]);

    //     }
    //   } catch (error) {
    //     console.warn(error, 'error try catch');
    //   }
    // },
    /**
     * 获取售后宝版本号
     */
    async getShbEdition () {
      const DefaultEdition = 1;
      let shbEdition = DefaultEdition;

      try {
        const Result = await SettingApi.getSettingEdition();
        const IsSuccess = Result.status == 0;
        const Edition = Result?.data?.edition || DefaultEdition;
        window.channel = Result?.data?.channel || '';

        shbEdition = IsSuccess ? Edition : DefaultEdition;
      } catch (error) {
        shbEdition = DefaultEdition;
        console.error('Caused: getShbEdition -> error', error);
      }

      window.shbEdition = shbEdition;

      this.loadedEdition = true;
      this.shbEdition = shbEdition;
      this.buildNavbarMenus();
      this.buildMoreMenus();
      this.checkFirstLoginShowVersionLimitDialog()
    },
    // 获取售后宝基础版权限
    async getBasicEditionAuth () {
      let basicEditionAuth = {}

      try {
        const { data } = await SettingApi.getBasicEditionAuth();
        if (data) basicEditionAuth = data;
      } catch (error) {
        console.error('Caused: getBasicEditionAuth -> error', error);
      }

      window.basicEditionAuth = basicEditionAuth;
    },
    // 获取售后宝基础版权限
    async getGrayAuth () {
      let grayAuth = {}

      try {
        const { result } = await SettingApi.getGrayAuth();
        if (result) {
          grayAuth = result;
          this.grayAuth = result
        }
      } catch (error) {
        console.error('Caused: getBasicEditionAuth -> error', error);
      }
      
      window.grayAuth = grayAuth;

    },
    // 获取自定义报表的灰度权限
    async getGrayCustomReport () {
      try {
        const { status, data } = await SettingApi.getGrayCustomReport();
        if(status == 0 && data){
          window.CUSTOM_REPORT = data;
        }
      } catch (error) {
        console.error('Caused: getBasicEditionAuth -> error', error);
      }
    },
    // 获取售后宝多语言列表 已舍弃
    async getLanguages () {
      let languages = []

      try {
        const { status, data } = await SettingApi.getLanguages();
        if (status === 0) languages = data;
      } catch (error) {
        console.error('Caused: getBasicEditionAuth -> error', error);
      }

      window.languages = languages;
    },
    pushTaskListIds (id) {
      this.taskListIds.push(id);
    },
    flashSomePage (arr = []) {
      try {
        for (let index = 0; index < this.frameTabs.length; index++) {
          if (arr.some(item => item.type == this.frameTabs[index].id)) {
            this.$platform.refreshTab(this.frameTabs[index].id);
          }
        }
      } catch (error) {
        console.warn(error, 'error try catch');
      }
    },
    switchTheme (themeClassSuffix) {
      setThemeClass(`theme-${themeClassSuffix ? themeClassSuffix : 'default'}`)
    },
    openTaskSettingGuide (url) {
      this.$refs.taskSettingGuide.open(url);
    },
    changeConfirmSetting () {
      this.confirmSetting = true;
    },
    /** 日程管理需求-日程初始化设置提醒 */
    planningTime () {
      this.$confirm(i18n.t('common.base.tip.planningTimeConfirmContent'), i18n.t('common.base.toast'), {
        type: 'warning'
      }).then(() => {
        // console.log('计划时间调整为'+this.planTimeTypeCode)
        this.planningTimeDialog = false;
        SettingApi.postSettingPlanTime({ planTimeTypeCode: this.planTimeTypeCode }).then((res) => {
          console.log(res)
        }).catch();
      });
    },
    // 设置当前组织名称
    async getUserServiceProviderSign () {
      const res = await NotificationApi.getUserServiceProviderSign({
        userId: this.loginUser.userId
      });

      if (res.status !== 0) return;
      this.isProviderSign = res.data;
      sessionStorage.setItem('isProviderSign', Number(res.data));
    },
    /** *
     * 查询客服状态
     */
    async getCustomerServiceStatus () {
      const { code, data } = await ImApi.getCustomerServiceStatus()
      if (code == 0) {
        this.serviceStatus = data.status
        this.serviceInfo = data || {};
        this.showCustomerServiceStatus = true
      } else {
        this.showCustomerServiceStatus = false
      }
    },
    // / 获取在线客服设置总开关状态
    async getImEnabled() {
      try {
        const { code, data = false } = await ImApi.getImEnabled();
        if (code !== 0) return;
        this.imEnabled = !!data;
      } catch (error) {
        console.error('error', error);
      }
    },
    /** *
     * 修改客服状态
     */
    async changeServiceStatus (status) {
      const { code, message } = await ImApi.modifyCustomerServiceStatus({
        status
      })
      if (code == 0) {
        this.getCustomerServiceStatus()
      } else {
        this.$platform.notification({
          title: i18n.t('common.base.tip.operationFail'),
          message,
          type: 'error',
        })
      }
    },
    getQueryString (name, url) {
      let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
      let search = url?.search || window.location.search
      let r = search.substr(1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
      return null;
    },
    hasShare () {
      // 清除分享链接
      {
        let shareUrl = window.location.href.split('shareUrl=')[1]
        if (shareUrl) {
          sessionStorage.setItem('shareUrl', decodeURIComponent(shareUrl))
          window.location.replace(window.location.origin)
          return
        }
      }
      // 跳转到分享链接
      {
        let shareUrl = sessionStorage.getItem('shareUrl')
        if (!shareUrl) return
        let url = new URL(shareUrl)
        const pathname = url.pathname
        // 事件详情页面
        if (pathname.indexOf('/event/view') != -1) {
          let eventId = this.getQueryString('id', url)
          openTabForEventView(eventId)
        } else if (pathname.indexOf('/task/view') != -1) {
          const index = pathname.lastIndexOf('/');
          const taskId = pathname.substring(index + 1, pathname.length).split('?')[0];
          openTabForTaskView(taskId)
        }
        sessionStorage.removeItem('shareUrl')
      }
    },
    // 获取报表权限
    async getReportAuth(){
      try {
        const { data } = await getReportAuth({authKey: 'VIP_REPORT_VIEW'});
        localStorage.setItem('is_report_auth', data || false);
      }catch(e){
        console.error('getReportAuth', e);
      }
    },
    initUserGuide(type) {
      let key = type;
      // 判断是否显示新手引导
      if (this.userGuideStroage && this.userGuideStroage[key] && this.userGuideStroage[key].isComplete == 0) {
        this[`${type}GuideDom`] && this[`${type}GuideDom`].$children[0].clearGuide()

        this.initIMGuide();
      }else{
        if(this.initData.user && this.initData.user.firstLogin == 2 ){
          this.userFeedbackGuide()
          return
        }
        this.$Guide([{
          domId: 'frame-user-profile-guide',
          id: type,
          title: i18n.t('common.guide.personalCenter.title'),
          content: type === 'edit-pwd-tour' ? i18n.t('common.guide.personalCenter.editPwd') : i18n.t('common.guide.personalCenter.switch'),
          stepTotalSetting:{
            leftBtn: i18n.t('common.base.skip'),
            finishBtn: i18n.t('common.base.ok'),
            needCover:true,
          }
        }], 0, '', (e) => {
          return new Promise((resolve, reject) => {
            
            if (e.type == 'left') {
              this.skipAllGuide()
              return Promise.resolve()
            }
            
            let nextGuideEnum = ['stop', 'finish'];
            if(nextGuideEnum.includes(e.type)){
              setTimeout(() => {
                this.userFeedbackGuide()
              }, 1000);
            }
            resolve();
          })
        }).create().then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: key,
                  step: 1,
                  isComplete: 0
                }
              ]
            }, this.userGuideStroage).then(res=>{
              this.userGuideStroage = res;
            });
            this[`${type}GuideDom`] = vueDom;
          }
        })
      }
    },
    // 已舍弃
    // completeUserGuide(type){
    //   const params = {}
    //   params.type = type
    //   params.step = 1
    //   params.isComplete = 1
    //   params.desc = ''
    //   GuideApi.setUserGuideStorage(params)
    // },
    checkModifyPwdGuide() {
      // this.$tours.modifyPwdTour.start()
      
      if (this.initData.isUpdatePassword && this.tenantType == 1) {
        // this.$tours.modifyPwdTour.start()
        this.$Guide([{
            domId: 'frame-user-profile-guide',
            id: 'user-need-edit-password-guide',
            content: i18n.t('common.base.tip.changePwd.content'),
            title: i18n.t('common.base.tip.changePwd.title'),
            apendToBody:true,
            stepTotalSetting:{
              leftBtn: i18n.t('common.base.skip'),
              finishBtn: i18n.t('common.base.ok'),
            }
          }], 0, '', (e) => {
            return new Promise((resolve, reject) => {
              
              if (e.type === 'left') {
                this.skipAllGuide()
                resolve();
                return
              }
              
              this.stopModifyPwdStep()
              resolve();
            })
          }).create().then(vueDom => {
          })
        
      }
    },
    // 智能计划引导
    initSmartPlanGuide() {
      // 判断灰度
      if (!this.smartPlanGray) {
        // 执行下一个引导

        return
      }
      // 判断是否完成
      let id = SMART_PLAN_GUIDE
      let isComplete = this.userGuideStroage?.[id]?.isComplete
      if (isComplete) {
        // 执行下一个引导

        return
      } 
      this.$nextTick(() => {
        this.smartPlanGuide()
      })
    },
    smartPlanGuide() {
      this.defaultActive = SMART_PLAN_TAB
      let id = SMART_PLAN_GUIDE
      let lastFinish = 1;
      let arr = [
        {
          title: this.$t('common.guide.smartPlan.content1'),
          content: this.$t('common.guide.smartPlan.content2'),
          haveStep: false,
          nowStep: 1,
          id,
          domObj: () => {
            return document.querySelector(`.menuKey-${SMART_PLAN_TAB}`);
          },
          needCover: true,
          lastFinish,
          stepTotalSetting:{
            finishBtn: this.$t('common.guide.smartPlan.content3'),
          }
        }
      ]
      this.$Guide(arr, 0, '', e => {
        this.defaultActive = SMART_PLAN_TAB
        const { type } = e
        if (type == 'finish') {
          this.openTab(SMART_PLAN_TAB)
        }
        return new Promise((resolve, reject) => {
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            }, this.userGuideStroage).then(res=>{
              this.userGuideStroage = res;
            });
          }
        });
    },
    /**
     * @des 所有工作台$guide引导均在此处理
     * 目前包含引导 
     * 新用户 --> [新用户引导, 个人中心, 意见反馈]
     * 老用户 --> [系统弹窗通知, 系统更新通知, 三级菜单设置引导]
     * $guide 引导 [个人中心, 意见反馈, 系统弹窗通知, 系统更新通知, 三级菜单设置引导,内部协同，专属客服]
     */
    mainViewGuideList(){
      getUserGuideStorageBase().then(res => {
        this.userGuideStroage = res;
        if (this.tenantType == 1) {
        // 多端自建的
          this.initUserGuide('edit-pwd-tour');
          this.getTenantInform();
        }else{
          this.$nextTick(() => {
            this.userFeedbackGuide()
          })
        }
      }).catch(err=>{
        if (this.tenantType == 1) {
        // 多端自建的
          this.initUserGuide('edit-pwd-tour');
          this.getTenantInform();
        }else{
          this.$nextTick(() => {
            this.userFeedbackGuide()
          })
        }
      })
    },
    /**
     * @des 用户引导关闭的钩子函数
     */
    closeUserGuide(){
      this.mainViewGuideList();
    },
    /**
     * @des 消息弹窗关闭的钩子
     */
    closeSystemPopup(){
      this.systemPopupShow = false;
    },
    updateWxUserName(){
      this.$refs.openDataRef.bind();
    },
    calendarTodayHandler() {
      
      if (!this.isShowTodayCalendar) return
      
      this.$refs.CalendarTodayView.fetchWorkbenchTodayCalendar()
    },
    onClickGoCalendarHandler(params) {
      closeTabCalendar()
      openTabCalendar()
    },
    // 折叠菜单栏
    frameHeaderBtn(){
      this.collapse = !this.collapse;
      
      this.bodyClassSet();
    },
    bodyClassSet(){
      const el = document.querySelector('body');
      
      if(!this.collapse){
        addClass(el, 'menu-open');
        removeClass(el, 'menu-fold');
      }else {
        addClass(el, 'menu-fold');
        removeClass(el, 'menu-open');
      }
    },
    /**
     * @des 获取当前系统的语言
     */
    getSystemLanguages(){
      getSystemLanguageList().then(res=>{
        if (res.code == 0 || res.status == 0) {
          let { data } = res;
          // 过滤b端语言
          let bArr = [];
          data = data.map(item=>{
            if(item.isToB){
              bArr.push(item)
            }
            let { languageKey, languageValue } = item;
            // 兼容老数据
            return {
              ...item,
              language:languageKey
            }
          })
          this.systemLanguageList = bArr;
          window.languages = data;
        } else {
          throw res
        }
        }).catch(err=>{
          console.warn('http erro',err);
          // this.$notify.error({
          //   title: '错误提示',
          //   message: err.message,
          //   duration: 2000,
          // });
        }).finally(()=>{
        })
    },
    getCurrencyList() {
      fetchCurrencyList().then(res => {
        if(res.status == 0) {
          let { data } = res;
          window.currencyList = data;
        }
      })
    },
    // 判断当前租户是否开启呼叫中心灰度功能
    async judgeCallCenterGray () {
      // 默认清空灰度和呼叫中心模块
      localStorage.setItem('call_center_gray', 0); //呼叫中心灰度 0未开启 1开启
      localStorage.setItem('call_center_module', 0); // 呼叫中心模块(是否有呼叫中心功能) 0没有 1有
      localStorage.setItem('call_center_agent', 0); // 是否绑定呼叫中心坐席 0不是 1是
      try {
        const { status, data } = await http.get('/setting/callCenterGray');
        if (status !== 0 || !data) {
          return;
        }
        if (data.callcenter) {
          // 说明开启呼叫中心灰度
          localStorage.setItem('call_center_gray', 1);
          return this.getAccountInfo();
        }
        console.log('未开通呼叫中心灰度')
      } catch (error) {
        console.error(error);
      }
    },
    // 获取呼叫中心类型
    async getAccountInfo () {
      try {
        const { code, result } = await CallCenterApi.getCallCenterAccountInfoUpdate();
        // result为null未申请开通
        if (code !== 0 || !result) {
          return;
        }
        let keys = Object.keys(result)
        if( keys.length>0 ){
          this.callCenterType = keys[0]
          localStorage.setItem('call_center_module', 1)
          console.log(`呼叫中心类型-${this.callCenterType}`)
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 内部协同IM引导
    initIMGuide() {
      const RootWindow = getRootWindow(window);
      if (!RootWindow?.grayAuth?.CHAT_IM) {
        this.initExclusiveCustomerServiceGuide()
        return
      };

      let id = 'im-guide';
      if (this.userGuideStroage && this.userGuideStroage[id]) {
        // 完成了内部协同引导
        this.initExclusiveCustomerServiceGuide()
        return
      };

      this.$nextTick(() => {
        this.imGuide();
      })
    },
    imGuide() {
      let id = 'im-guide';
      let lastFinish = 1;
      let arr = [
        {
          content: this.$t('common.guide.im.content1'),
          haveStep: true,
          direction: 'row',
          nowStep: 1,
          id,
          domObj: () => {
            return document.querySelector('.frame-header-btn-notice-content');
          },
          needCover: true,
          lastFinish,
          show: true,
          stepTotalSetting: {
            leftBtn: this.$t('common.base.skip'),
          }
        },
        {
          content: this.$t('common.guide.im.content2'),
          haveStep: true,
          nowStep: 2,
          id,
          domObj: () => {
            return document.querySelector('#tab-second');
          },
          needCover: true,
          lastFinish,
          show: true, // 本来快捷入口是需要判断工作台灰度的，但等这次上线的时候灰度会放开
        },
        {
          content: this.$t('common.guide.im.content3'),
          haveStep: true,
          nowStep: 3,
          id,
          domObj: () => {
            return document.querySelector('.im-add');
          },
          needCover: true,
          lastFinish,
          show: true,
        },
        {
          content: this.$t('common.guide.im.content4'),
          haveStep: true,
          nowStep: 4,
          id,
          domObj: () => {
            return document.querySelector('.base-select-user-footer > .el-button--primary');
          },
          diyClass:'im-guide-with-select-user',
          needCover: true,
          finishBtn: this.$t('common.base.finish'),
          show: true,
        },
      ].filter(item => item.show);
      this.$Guide(arr, 0, '', e => {
        
        const { type, nowStep } = e;

        if (type === 'left') {
          this.skipAllGuide()
          return Promise.resolve()
        }
        
        if (type === 'next') {
          if (nowStep == 0) {
            this.$nextTick(() => {
              this.openNotificationCenter();
            })
          } else if (nowStep == 1) {
            this.$refs.notification.activeName = 'second';
          } else if (nowStep == 2) {
            this.$refs.notification.showPop();
          }
        }
        return new Promise((resolve, reject) => {
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            }, this.userGuideStroage).then(res=>{
              this.userGuideStroage = res;
            });
          }
        });
    },
    handleCloseMenuBarGuide() {
      this.initIMGuide();
    },
    onMenuBarGuideLeftClick() {
      this.skipAllGuide();
    },
    showChatModal(){
      if(!this.exclusiveCsIM) return
      if(!this.isLoadChatModal){
        this.isLoadChatModal = true
      }

      this.$nextTick(()=>{
        this.$refs.OnlineChatModal.openChat()
      })
    },
    /**
     * 专属客服引导
     */
    initExclusiveCustomerServiceGuide(){
      // 判断灰度
      if(!this.exclusiveCsIM) {
        // 执行下一个引导
        this.initSmartPlanGuide()

        return
      }

      // 判断是否完成
      let id = EXCLUSIVE_CUSTOMER_SERVICE_GUIDE_ID;
      let isComplete = this?.userGuideStroage?.[id]?.isComplete
      if (isComplete) {
        // 执行下一个引导
        this.initSmartPlanGuide()
        
        return
      }

      this.$nextTick(()=>{
        this.exclusiveCustomerServiceGuide()
      })
    },
    exclusiveCustomerServiceGuide() {
      let id = EXCLUSIVE_CUSTOMER_SERVICE_GUIDE_ID;
      let lastFinish = 1;
      let arr = [
        {
          content: this.$t('common.guide.im.content5'),
          haveStep: false,
          nowStep: 1,
          left:50,
          id,
          domObj: () => {
            return document.getElementById('exclusiveCsChat');
          },
          needCover: true,
          lastFinish,
          stepTotalSetting:{
            finishBtn: this.$t('common.base.ok'),
            leftBtn: this.$t('common.base.skip'),
          }
        }
      ]
      this.exclusiveCustomerServiceVisible = true
      this.$Guide(arr, 0, '', e => {
        
        if (e.type === 'left') {
          this.skipAllGuide()
          return Promise.resolve()
        }
        
        return new Promise((resolve, reject) => {
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            }, this.userGuideStroage).then(res=>{
              this.userGuideStroage = res;
            });
          }
        });
    },
    getRobotList() {
      getRobotList().then(result => {
        const data = result?.data || [];
        this.robotList = data;
      })
    },
    getWatermark() {
      UserCardApi.getWatermark().then(res => {
        if (res.success) {
          this.watermaskContent = res.data || ''
        }
      }).catch(err => console.error(err))
    },
    changeAllFormBuilderCell(number){
      this.allFormBuilderCell = number
      this.frameTabs.forEach(item=>{
        let iframe = document.getElementById(`frame_tab_${item.id}`);
        if(iframe){
          iframe.contentWindow?.postMessage({
            action: 'changeAllFormBuilderCell',
            number
          }, '*');
        }
      })
      this.updateAllFormBuilderCellForHttp(AllFormBuilderCellStorageKey, number)
    },
    getAllFormBuilderCell(){
      return this.allFormBuilderCell
    },
    async initAllFormBuilderCell(type){
      try {
        let res = await getServerCachApi(type || AllFormBuilderCellStorageKey)
        if(res.status == 0 && res.data?.length && res.data?.[0]?.userConfig){
          if(type === AllViewLayoutStorageKey) {
            const data = JSON.parse(res.data?.[0]?.userConfig) ?? {}
            this.changeAllViewLayout(data)
          } else {
            this.changeAllFormBuilderCell(res.data?.[0]?.userConfig * 1)
          }
        }
      } catch (error) {
        console.error(error, 'initAllFormBuilderCell is Error')
      }
    },
    updateAllFormBuilderCellForHttp:debounce(function(type, number){
      creatServerCachApi({
        isComplete: 1,
        step: 1,
        type,
        userConfig: number
      })
    }, 500),
    changeAllViewLayout(data){
      this.allViewLayout = data
      this.frameTabs.forEach(item=>{
        let iframe = document.getElementById(`frame_tab_${item.id}`);
        if(iframe){
          iframe.contentWindow?.postMessage({
            action: 'changeAllViewLayout',
            data
          }, '*');
        }
      })
      this.updateAllFormBuilderCellForHttp(AllViewLayoutStorageKey, JSON.stringify(data))
    },
    getAllViewLayout() {
      return this.allViewLayout
    },
    initAllViewLayout() {
      this.initAllFormBuilderCell(AllViewLayoutStorageKey)
    },
    initBizChatPanelChat() {
      this.$refs.BizChatPanel.outsideInit();
    },
    async fetchQuestionDeleteImpl(questionId, fromId) {
      
      const isSuccess = await this.fetchQuestionDelete({
        ids: [questionId]
      })
      
      if (isSuccess) {
        this.refreshFromTab(fromId)
      }
      
    },
    refreshFromTab(fromId) {
      platform.refreshTab(fromId);
    },
    initOffSiteLogin() {
      // 是否显示异地登录提醒
      const showRemoteLoginRemind = Boolean(this.initData?.showRemoteLoginRemind)
      if (showRemoteLoginRemind) {
        this.$refs.OffSiteLoginDialog.open();
      }
    },
    /** 导出下载 */
    exportDownload(item) {
      downloadByhref({href:`${location.port !== '' ? '/serve' : ''}/excels/download?id=${item.id}`, name:item.name})
      item.isDownloaDongoing = 1;
    },
    onUserProfileClickHandler() {
      
      const showConsoleCount = 20;
      
      this.counter += 1;
      
      if (this.counter == showConsoleCount) {
        window.isShowConsole = true;
        clearTimeout(this.timer);
      }

      this.timer = setTimeout(() => {
        this.counter = 1
      }, showConsoleCount * 1000);
      
    },
    /**
     * @description 跳过首页出现的引导
     */
    async skipAllGuide() {
      this.isSkipAllGuide = true
      this.removeAllGuideComponent()
      await this.skipUserGuide()
      await this.skipUserFeedbackGuide()
      await this.skipIMGuide()
      await this.skipExclusiveCustomerServiceGuide()
    },
    skipUserGuide() {
      const key = 'edit-pwd-tour'
      return (
        setUserGuideStorageBase({
          userGuideList: [
            {
              type: key,
              step: 1,
              isComplete: 0
            }
          ]
        }, this.userGuideStroage).then(res=>{
          this.userGuideStroage = res;
        })
      )
    },
    skipUserFeedbackGuide() {
      
      this.initData.user.firstLogin = 1
      this.showUserFeedbackGuide = false
      
      const key = newProductGuideStore.USER_FEED_BACK
      return (
        setUserGuideStorageBase(
          {
            userGuideList: [
              {
                type: key,
                step: 1,
                isComplete: 0
              }
            ]
          }, 
          this.userGuideStroage
        ).then(res => {
          this.userGuideStroage = res
        })
      )
    },
    skipIMGuide() {
      const key = 'im-guide'
      return (
        setUserGuideStorageBase({
          userGuideList: [
            {
              type: key,
              step: 1,
              isComplete: 1
            }
          ]
        }, this.userGuideStroage).then(res=>{
          this.userGuideStroage = res;
        })
      )
    },
    skipExclusiveCustomerServiceGuide() {
      const key = EXCLUSIVE_CUSTOMER_SERVICE_GUIDE_ID
      return (
        setUserGuideStorageBase({
          userGuideList: [
            {
              type: key,
              step: 1,
              isComplete: 1
            }
          ]
        }, this.userGuideStroage).then(res=>{
          this.userGuideStroage = res;
        })
      )
    },
    removeAllGuideComponent() {
      const guideComponents = document.querySelectorAll('.guide-component');
      guideComponents.forEach(item => {
        item.remove();
      });
    }
  },
  created () {
    this.initAllFormBuilderCell()
    this.initAllViewLayout()
    // TODO: 迁移完成后删除
    window.updateUserState = this.updateUserState;
    window.showExportList = this.checkExports;
    window.exportPopoverToggle = this.exportPopoverToggle;
    window.pushTaskListIds = this.pushTaskListIds;
    window.loginUser = this.loginUser;
    window.getUserTaskGray = this.getUserTaskGray;
    window.isSystemAdmin = this.isSystemAdmin;
    window.getGlobalRootInstance = () => this;
    window.openSaleManager = this.openSaleManager;
    window.changeAllFormBuilderCell = this.changeAllFormBuilderCell
    window.getAllFormBuilderCell = this.getAllFormBuilderCell
    window.changeAllViewLayout = this.changeAllViewLayout
    window.getAllViewLayout = this.getAllViewLayout

    window.getRobotList = this.getRobotList;
    window.initBizChatPanelChat = this.initBizChatPanelChat;
    window.fetchQuestionDelete = this.fetchQuestionDeleteImpl;
    window.openDingtalkAuth = openDingtalkAuth;
    
    window.resizeFrame = function () {
      console.warn('此方法只用于兼容旧页面，无实际效果，不推荐调用');
    };
    window.toggleTable = () => {
      this.collapse = false
    },
    window.flashSomePage = this.flashSomePage;
    this.clearCachedIds();
    sessionStorage.removeItem('shb_systemMsg');

    this.getSystemMsg();
    setInterval(() => {
      this.getSystemMsg();
    }, NOTIFICATION_TIME);

    this.switchTheme()
    // 查询在线客服开通状态
    this.getImOpenState()
    window.openUserFeedBack = this.openUserFeedBack
    this.getImInitData()
    this.getSchedulingData()
    this.getSettleData()
    this.getCustomerServiceStatus()
    this.getImEnabled()
    this.getShowUserCard()
    this.getSystemLanguages()
    this.getCurrencyList()

    // 获取初始化权限和版本信息
    this.getInitAuth()
    this.getWatermark()

    // websocket通知修改客服状态
    this.$eventBus.$on('changeCustomerServiceStatus', this.getCustomerServiceStatus)
    this.$eventBus.$on('wx-sign-done', this.updateWxUserName)
    // websocket通知客服休息
    this.$eventBus.$on('serviceOffWork', this.serviceOffWork);
  },
  async mounted () {
    this.$nextTick(()=>{
      const { tenantType, IS_WECHAT_NAME } = this.initData;
      this.isOpenData = tenantType == 2 && IS_WECHAT_NAME == 1;
    });

    // 获取初始化权限和版本信息
    this.getInitAuth()
    this.getGrayCustomReport()

    // 当个人中心修改了用户信息，这边需要更新
    window.addEventListener('message', event=>{
      // 升级智能计划操作
      if (event?.data == 'upgradeToSmartPlan') {
        return this.upgradeToSmartPlan()
      }
      const { userPic, displayName } = event.data || {};
      userPic && (this.loginUser.head = userPic);
      displayName && (this.loginUser.displayName = displayName);
    });
    localStorage.setItem('openWeChatService', this.initData.openWeChatService ? 1 : 0);
    localStorage.setItem('userId', this.initData.user.userId);
    localStorage.setItem('tenantType', this.initData.tenantType || 0);
    localStorage.setItem('superAdmin', this.loginUser.superAdmin || '');
    if(this.initData.tenantType == 0 || this.initData.tenantType == 2) {
      localStorage.setItem('useStateBlackList', this.initData.stateBlackList?.length ? 1 : 0);
    }
    let userGuide = this?.initData?.userGuide === true || false;
    if (userGuide && !this.isAuthMode) {
      this.$refs.userGuideView.show();
    }else{
      this.mainViewGuideList();
    }

    if(this.initData.tenantType == 4 && this.initData.isPay !== 1 && localStorage.getItem('lark_login')=='true') {
      try {
        larkPopDisplay().then(res=>{
          if(res.status == 0){
            this.showLarkTrailTop = res.data?.top || false
            localStorage.setItem('lark_trail',this.showLarkTrailTop)
            this.tenantName = res.data?.tenantName || ''
            if(res.data?.pop){
              this.$nextTick(()=>{
                this.$refs.larkApplyTrailFeature?.showApplyDialog()
              })
            }
          }
        })
      } catch (error) {
        console.error(error)
      }
    }

    /** * 部分页面引导 数据处理  s*/
    if (this?.initData?.needResetGuide) {
      let needResetGuideArr = this?.initData?.needResetGuide;

      needResetGuideArr.forEach((item) => {
        try {
          Object.keys(GuideStoreObj[item]).forEach((items) => {
            localStorage.setItem(GuideStoreObj[item][items], '-1');
          });
        } catch (error) { }
      });
    }

    if (this?.initData?.needGuide) {
      let needGuideArr = this?.initData?.needGuide;
      // let needGuideArr = ['newTaskGuideStore'];
      needGuideArr.forEach((item) => {
        try {
          Object.keys(GuideStoreObj[item]).forEach((items) => {
            localStorage.setItem(GuideStoreObj[item][items], '-1');
          });
        } catch (error) { }
      });
    }

    if (this?.initData?.needClearGuide) {
      let needClearGuideArr = this?.initData?.needClearGuide;
      // let needGuideArr = ['newTaskGuideStore'];
      needClearGuideArr.forEach((item) => {
        try {
          Object.keys(GuideStoreObj[item]).forEach((items) => {
            localStorage.removeItem(GuideStoreObj[item][items]);
          });
        } catch (error) { }
      });
    }
    /** * 部分页面引导 数据处理  e*/
    this.checkExports({init: true});

    this.getUserServiceProviderSign();

    this.getConfig()
    this.getReportAuth();
    // 判断是否带有分享链接
    this.hasShare()
    this.checkModifyPwdGuide()
    
    this.calendarTodayHandler()
    // 是否显示退出按钮 AB环境切换没有走登录的时候获取不到isShowLogout
    this.isShowLogout = !(localStorage.getItem('isShowLogout') === 'false')
    
    // 给body设置类名
    this.bodyClassSet();

    // 查询呼叫中心开通信息
    this.judgeCallCenterGray()
    
    this.initOffSiteLogin()
    
    // 判断是否允许切换语言包 老版本不限制，新版本只有国际化账号才允许切换语言包
    if(this.rootWindowInitData.cloudVersion) {
      this.allowSwitch = Boolean(this.rootWindowInitData?.user?.accountType)
    }
    
    try {
      this.getRobotList()
    } catch (error) {
      console.error(error)
    }
    
  },
  components: {
    DynamicInfo,
    draggable,
    [FrameNav.name]: FrameNav,
    [FrameTab.name]: FrameTab,
    FrameTabGroup,
    [Privacy.name]: Privacy,
    [Version.name]: Version,
    [SystemPopup.name]: SystemPopup,
    [SaleManager.name]: SaleManager,
    [NotificationCenter.name]: NotificationCenter,
    [ImportAndExport.name]: ImportAndExport,
    [UserGuide.name]: UserGuide,
    [switchCompaniesDialog.name]: switchCompaniesDialog,
    [ComponentNameEnum.WeiXinApplyTrailFeature]: WeiXinApplyTrailFeature,
    [CreateFeedBackDialog.name]: CreateFeedBackDialog,
    [FeedBackListDialog.name]: FeedBackListDialog,
    DocumentQuote,
    [GlobalWebSocket.name]: GlobalWebSocket,
    CustomerServiceStatus,
    callCenter,
    [PersonalVersionOpeningGuide.name]: PersonalVersionOpeningGuide,
    [CallCenterZhiChi.name]: CallCenterZhiChi,
    ExpressEntrance,
    [CalendarTodayView.name]: CalendarTodayView,
    MenuBarGuide,
    [LarkApplyTrailFeature.name]:LarkApplyTrailFeature,
    CallCenterTianRun,
    OnlineChatModal,
    NewBlurGuide,
    OffSiteLoginDialog,
  },
};
</script>

<style lang="scss" src="./frame.scss"></style>
